package com.xzq.erp.config;

import com.xzq.erp.filter.JwtAuthenticationFilter;
import com.xzq.erp.handler.RestAccessDeniedHandler;
import com.xzq.erp.handler.RestAuthenticationEntryPoint;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity // 启用Spring Security
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final RestAccessDeniedHandler accessDeniedHandler;
    private final RestAuthenticationEntryPoint authenticationEntryPoint;
    
    /**
     * 开发环境安全配置
     */
    @Bean
    @Profile("dev")
    public SecurityFilterChain devSecurityFilterChain(HttpSecurity http) throws Exception {
        configureCommon(http);
        
        http.authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/auth/**").permitAll()  // 公开登录和注册端点
                .requestMatchers("/doc.html", "/webjars/**", "/swagger-ui.html",
                        "/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**").permitAll()  // 公开Swagger文档
                 .requestMatchers("/ai/**").permitAll()  // AI接口放行自己定义拦截器
                .anyRequest().authenticated()  // 其他请求需要认证
        );
        return http.build();
    }
    
    /**
     * 生产环境安全配置
     */
    @Bean
    @Profile("prod")
    public SecurityFilterChain prodSecurityFilterChain(HttpSecurity http) throws Exception {
        configureCommon(http);
        
        http.authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/auth/**").permitAll()  // 公开登录和注册端点
            .requestMatchers("/doc.html", "/webjars/**", "/swagger-ui.html", 
                "/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**").permitAll()  // 公开Swagger文档
            .requestMatchers("/ai/**").authenticated()  // AI接口需要认证但不需要特定权限
            // 管理员可以访问所有接口
            .requestMatchers("/**").hasRole("ADMIN")
            .anyRequest().authenticated()  // 其他请求需要认证
        );
        
        return http.build();
    }
    
    /**
     * 通用安全配置
     */
    private HttpSecurity configureCommon(HttpSecurity http) throws Exception {
        http
            .csrf(AbstractHttpConfigurer::disable)  // 禁用CSRF保护
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))  // 不使用Session
            .exceptionHandling(exception -> exception
                .accessDeniedHandler(accessDeniedHandler)  // 权限拒绝处理器
                .authenticationEntryPoint(authenticationEntryPoint)  // 认证失败处理器
            )
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);  // 添加JWT过滤器
            
        return http;
    }
    
    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    /**
     * 认证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }
} 